﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;

namespace RedisNet
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            IServiceCollection services = new ServiceCollection();
            IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();
            // 将 IConfiguration 注册到服务容器
            services.AddSingleton(config);
            //// 注册 Redis 单例连接
            //services.AddSingleton<IConnectionMultiplexer>(sp =>
            //{
            //    // 获取 Redis 配置部分
            //    var redisConfiguration = config.GetSection("Redis");

            //    // 获取 Redis 连接字符串
            //    var redisConnectionString = redisConfiguration["ConnectionString"];

            //    // 配置 Redis 连接选项
            //    var redisConfigurationOptions = ConfigurationOptions.Parse(redisConnectionString);
            //    redisConfigurationOptions.AbortOnConnectFail = true;  // 连接失败抛出异常
            //    redisConfigurationOptions.ConnectRetry = 3;            // 重试次数
            //    redisConfigurationOptions.ConnectTimeout = 5000;       // 5秒超时

            //    // 返回 Redis 连接
            //    return ConnectionMultiplexer.Connect(redisConfigurationOptions);
            //});
            //// 注册 Redis 数据库实例（可选）
            //services.AddSingleton(sp =>
            //    sp.GetRequiredService<IConnectionMultiplexer>().GetDatabase()
            //);
            services.Configure<RedisConfigOptions>(config.GetSection("RedisConfig"));
            services.AddSingleton<RedisClient>();

            services.AddSingleton(typeof(RedisService));
            services.AddSingleton(typeof(DemoService));
            // 构建服务提供器
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            DemoService demo = serviceProvider.GetRequiredService<DemoService>();
            await demo.Test();
            Console.ReadKey();
        }
    }
}
